﻿using Microsoft.Extensions.Logging;
using Service.Core.Repository.Core;
using Service.Framework.ApplicationEventBus;
using Service.Framework.OperationLog;

namespace Service.Core.Repository.Event
{
    public class OperationLogHandle : IApplicationEventHandler<OperationLogAges>
    {
        private readonly ILogger<OperationLogHandle> logger;
        private readonly IRepository<OperationLog> repository;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="logger"></param>
        public OperationLogHandle(ILogger<OperationLogHandle> logger, IRepository<OperationLog> repository)
        {
            this.logger = logger;
            this.repository = repository;
        }

        public async Task Handle(OperationLogAges @event)
        {
            logger.LogInformation("SavaDbOperationLog");
            await repository.Db.Insertable(ConvertToOperationLog(@event.OperationLogDto)).SplitTable().ExecuteCommandAsync();
        }


        public OperationLog ConvertToOperationLog(OperationLogDto dto)
        {
            return new OperationLog(
                      dto.Msg,
                      dto.ApiMethod,
                      dto.ApiPath,
                      dto.ElapsedMilliseconds,
                      dto.Params,
                      dto.Result,
                      dto.BrowserInfo,
                      dto.Ip,
                      dto.Name,
                      dto.Type,
                      dto.UserId,
                      dto.ClientId,
                      dto.DevicePlatform,
                      dto.DeviceId,
                      dto.Version
                  );
        }
    }
}
